import time

import jwt
from django.conf import settings
from django.http import JsonResponse

from user.models import User
from .response_code import get_resp_dict


def make_token(user_id, expire=3600 * 24):
    """
    根据用户ID生成token
    :param user_id: 用户ID
    :param expire: token有效期
    :return: 返回生成的token
    """
    # 1 准备payload
    now = time.time()
    payload = {
        'user_id': user_id,
        'exp': expire + now
    }
    # 2 准备key
    key = settings.JWT_TOKEN_KEY
    # 3 生成token并返回 返回类型：bytes
    return jwt.encode(payload, key)


def get_user(request):
    """
    根据请求对象中的Token获取user model
    :param request: 请求对象
    :return: 返回user model
    """
    # 1 获取token
    token = request.META.get('HTTP_AUTHORIZATION')
    if not token:
        return None
    # 2 校验token
    try:
        payload = jwt.decode(token, settings.JWT_TOKEN_KEY)
    except Exception as e:
        print(e)
        return None
    # 3 从payload获取用户ID
    user_id = payload['user_id']
    user = User.objects.get(id=user_id)
    # 4 返回user
    return user


def check_token(fn):
    """
    装饰器函数，用来验证token有效性
    :param fn: 被装饰的函数
    :return: 返回一个包裹器
    """

    def wrap(request, *args, **kwargs):
        # 1 获取user
        user = get_user(request)
        if not user:
            result = get_resp_dict(code=403)
            return JsonResponse(result)
        # 2 将user以附加数据的方式保存到request对象中
        request.user = user
        # 3 调用装饰器修饰的函数
        return fn(request, *args, **kwargs)

    return wrap
